package edu.cmu.ece.ds.droidchat.controller;

import java.util.ArrayList;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import edu.cmu.ece.ds.droidchat.NetworkService;
import edu.cmu.ece.ds.droidchat.R;
import edu.cmu.ece.ds.droidchat.model.ChatSessionInfo;
import edu.cmu.ece.ds.droidchat.model.UserInfo;
import edu.cmu.ece.ds.droidchat.util.Toolbox;

public class ChatSessionListBaseAdapter extends BaseAdapter {

    private static final String TAG = "ChatSessionListBaseAdapter";

    // the chat sessions
    private ArrayList<ChatSessionInfo> chatSessionArray;

    private LayoutInflater mInflater;

    public ChatSessionListBaseAdapter(Context context,
            ArrayList<ChatSessionInfo> chatSessionArray) {
        this.chatSessionArray = chatSessionArray;
        mInflater = LayoutInflater.from(context);
    }

    public int getPositionInList(String chatSessionId) {
        int arraySize = chatSessionArray.size();
        for (int i = 0; i < arraySize; i++) {
            if (chatSessionArray.get(i).getSessionid().equals(chatSessionId)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int getCount() {
        return chatSessionArray.size();
    }

    @Override
    public Object getItem(int position) {
        return chatSessionArray.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.chat_sessions_list_item,
                    null);
            holder = new ViewHolder(this);
            holder.chatSessionNameTextView = (TextView) convertView
                    .findViewById(R.id.chat_session_name);
            holder.infoLineTextView = (TextView) convertView
                    .findViewById(R.id.chat_session_info);
            holder.newMessagePendingImageView = (TextView) convertView
                    .findViewById(R.id.chat_session_new_message_pending);

            // Invitation Acceptance layout
            holder.chatSessionDecisionLayout = (LinearLayout) convertView
                    .findViewById(R.id.chat_session_decision_layout);
            holder.acceptButton = (Button) convertView
                    .findViewById(R.id.chat_session_accept_button);
            holder.declineButton = (Button) convertView
                    .findViewById(R.id.chat_session_decline_button);
            holder.acceptButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    holder.respondToInvitation(true);
                }
            });
            holder.declineButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    holder.respondToInvitation(false);
                }
            });
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final ChatSessionInfo csInfo = chatSessionArray.get(position);
        Log.e(TAG, "csInfo=" + csInfo + ",@position=" + position);

        holder.chInfo = Toolbox.getChatSession(csInfo.getSessionid());

        holder.chatSessionNameTextView.setText(csInfo.getChatSessionName());
        if (csInfo.isPendingForMyInvitation()) {
            Log.e(TAG, "pending for invitation");
            holder.infoLineTextView.setVisibility(View.VISIBLE);
            holder.infoLineTextView.setText(R.string.response_pending);
            // holder.chatSessionNameTextView.setTextColor(Color.GRAY);
        } else if (csInfo.isPendingForMyResponse()) {
            Log.e(TAG, "pending for response");
            /*holder.chatSessionDecisionLayout.setVisibility(View.VISIBLE);
            holder.infoLineTextView.setVisibility(View.VISIBLE);
            holder.infoLineTextView.setText(R.string.waiting_for_response);*/
            // holder.chatSessionNameTextView.setTextColor(Color.GRAY);
        } else {
            // normal status
            Log.e(TAG, "normal!!!!!!!!!!!!!!!!!!!!!!!");
            holder.infoLineTextView.setVisibility(View.GONE);
        }
        if (csInfo.getNewMessagesCount() != 0) {
            // Log.e(TAG, "HERE!! "+csInfo.getNewMessagesCount());
            holder.newMessagePendingImageView.setText(""
                    + csInfo.getNewMessagesCount());
            holder.newMessagePendingImageView.setVisibility(View.VISIBLE);
        } else {
            holder.newMessagePendingImageView.setVisibility(View.GONE);
        }
        return convertView;
    }

    public static class ViewHolder {
        ChatSessionListBaseAdapter adapter;
        ChatSessionInfo chInfo;
        TextView chatSessionNameTextView;
        TextView infoLineTextView;
        TextView newMessagePendingImageView;
        LinearLayout chatSessionDecisionLayout;
        Button acceptButton;
        Button declineButton;

        ViewHolder(ChatSessionListBaseAdapter adapter) {
            this.adapter = adapter;
        }

        public void showNewMessagePendingImageView(boolean isPending,
                int unreadMessageCount) {
            if (isPending) {
                newMessagePendingImageView.setText("" + unreadMessageCount);
                if (unreadMessageCount >= 100) {
                    newMessagePendingImageView.setText("!");
                }
                newMessagePendingImageView.setVisibility(View.VISIBLE);
            } else {
                newMessagePendingImageView.setVisibility(View.GONE);
            }
            newMessagePendingImageView.invalidate();
        }

        public void showInfoLine(boolean show) {
            if (show) {
                infoLineTextView.setVisibility(View.VISIBLE);
            } else {
                infoLineTextView.setVisibility(View.GONE);
            }
            infoLineTextView.invalidate();
        }

        public void respondToInvitation(boolean accept) {
            chatSessionDecisionLayout.setVisibility(View.GONE);
            chInfo.setPendingForMyResponse(false);
            NetworkService ns = Toolbox.getService();
            if (ns != null) {
                ns.respondToChatInvitation(chInfo.getSessionid(),
                        chInfo.getInviter(), accept);
                if (accept) {
                    // accept it and start chat window activity
                    // chatSessionNameTextView.setTextColor(R.color.user_nickname);

                    // should probably add inviter into the participants here
                    UserInfo u = Toolbox.retrieveUserInfoByUsername(chInfo
                            .getInviter());
                    chInfo.addParticipant(u.getUsername(), u.getUserIP());

                    // should probably also remove inviter from ChatSessionInfo
                    chInfo.setInviter(null);

                    Toolbox.createChatWindowActivity(
                            chatSessionNameTextView.getContext(), false,
                            chInfo.getSessionid());
                } else {
                    //Toolbox.removeChatSession(chInfo.getSessionid());
                	Toolbox.removeChatSession(chInfo.getSessionid(), true);
                    adapter.chatSessionArray.clear();
                    adapter.chatSessionArray.addAll(Toolbox
                            .getAllChatSessions());
                }
            } else {
                // NetworkService doesn't exist!
                Log.e(TAG, "NetworkService doesn't exist!");
            }
            adapter.notifyDataSetChanged();
        }
    }

}
